package com.translate.web.api.controller;

import java.math.BigDecimal;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.translate.entity.PayManager;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;

import com.param.impl.IdPageParam;
import com.translate.vo.OrderInfoVO;
import com.translate.vo.TranslateVO;
import com.response.vo.ResponseModel;
import com.controller.base.AbstractCommonController;
import com.translate.web.param.TranslateUpdateParam;
import com.translate.web.param.contract.IIdAndUserIdParam;
import com.translate.web.param.IdAndUserIdParam;
import com.translate.web.param.TranslateAddParam;
import com.translate.entity.NoticeCenter;
import com.translate.entity.Translate;
import com.translate.entity.User;
import com.translate.web.service.INoticeCenterService;
import com.translate.web.service.IOrderInfoService;
import com.translate.web.service.IPayManagerService;
import com.translate.web.service.IRechargeService;
import com.translate.web.service.IServiceTypeService;
import com.translate.web.service.ITranslateService;
import com.translate.web.service.IUserService;
import com.basic.service.contract.IBaseService;
import com.constant.TransactionConst;

@RestController
@RequestMapping("translate")
public class TranslateController extends AbstractCommonController<Translate, IdPageParam> {
	private ITranslateService service;

	private IPayManagerService payManagerService;
	
	private IRechargeService rechargeService;
	
	IUserService userService;
	
	INoticeCenterService centerService;
	
	IServiceTypeService serviceTypeService;
	
	
	private IOrderInfoService[] orderInfoServer = new IOrderInfoService[2] ;
	
	@Resource
    public void setServiceTypeService(IServiceTypeService serviceTypeService) {
        this.serviceTypeService = serviceTypeService;
    }
	
	@Resource
	public void setCenterService(INoticeCenterService centerService) {
		this.centerService = centerService;
	}

	@Resource
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
	
	@Resource
	public void setRechargeService(IRechargeService rechargeService) {
		this.rechargeService = rechargeService;
		orderInfoServer[0] = rechargeService;
	}

	public TranslateController(ITranslateService service) {
		this.service = service;
	}

	
	/**
	 * 查看发票
	 * @param userIdParam
	 * @return
	 */
	@PostMapping("/lookDetail")
	public ResponseModel<TranslateVO> lookDetail(
			@RequestBody @Validated IdAndUserIdParam userIdParam,
			NativeWebRequest request
	) {
		
		long userId = this.getUserId(request);
		userIdParam.setUserId(userId);
		
		return ResponseModel.<TranslateVO>success(this.service.getTranslate(userIdParam, TranslateVO.class));
		
	}
	
	/**
	 * 添加
	 * @param <V>
	 * @param param
	 * @return
	 */
	@PostMapping("/add")
	@Transactional
	public ResponseModel<Integer> insert(@RequestBody @Validated TranslateAddParam param,
			NativeWebRequest httpServletRequest) {
		
		long userId = this.getUserId(httpServletRequest);
		
		User userInfoToCache = userService.getUserInfoToCache((int)userId);
		
		Byte isRegimental = userInfoToCache.getIsRegimental();
		
		Integer teamId = userInfoToCache.getTeamId();
		if (0 == isRegimental && null != teamId && 0 != teamId && 1 == userInfoToCache.getStatus()) {
			// 是团员 不是团长 不能开票
			return ResponseModel.<Integer>errorMsg(0, "您不是团长，不能开票");
		}
		
		
		IIdAndUserIdParam userIdParam = new IdAndUserIdParam();
		
		userIdParam.setId(param.getAssocId());
		
		userIdParam.setUserId(userId);
		
		IOrderInfoService orderInfoService = orderInfoServer[param.getType()];
		
		OrderInfoVO orderInfo = orderInfoService.getOrderInfo(userIdParam, OrderInfoVO.class, isRegimental, teamId);
		
		if (null == orderInfo) {
			return ResponseModel.<Integer>errorMsg(0, "订单信息不存在");
		}
		
		String realname = httpServletRequest.getAttribute("realname", RequestAttributes.SCOPE_REQUEST).toString();
		param.setUserName(realname);
		
		param.setUserId((int) userId);
		
		param.setMobile(httpServletRequest.getAttribute("mobile", RequestAttributes.SCOPE_REQUEST).toString());
		
		String orderSnId = orderInfo.getOrderSnId();
		param.setOrderSn(orderSnId);
		
		Integer serviceId = orderInfo.getServiceId();
		param.setServiceId(serviceId);
		
		BigDecimal money = orderInfo.getMoney();
		param.setMoney(money);
		
		String dutyParagraph = param.getDutyParagraph();
		
		if (null == dutyParagraph) {
			param.setDutyParagraph("");
		}
		Translate translate = new Translate();
		BeanUtils.copyProperties(param,translate);
		Translate serviceTranslate = service.getTranslate(translate);
		if (ObjectUtils.isEmpty(serviceTranslate)) {
			int id = this.service.parseInsert(param, Translate.class);
		} else {
			translate.setAuditStatus((byte) 0);
			translate.setId(serviceTranslate.getId());
			translate.setUpdateTime(System.currentTimeMillis());
			this.service.updateByPrimaryKeySelective(translate);
		}


		orderInfoService.updateTraslate(param.getAssocId());
		
		// 向管理端 张三(ID:12345678)【服务名称】订单ZF202xxxxxxxXXXX申请【发票】，请及时查当用户端点击【申请开票】后，管理端收到开票消息推送看处理!
		
		NoticeCenter center = new NoticeCenter();

		center.setUserId((int) userId);

		String content = realname+"(ID:" + userId + ")";
		
		String title = "", personal= "";
		
		// 发票类型 0 未知 1 预存发票 2 订单发票
		byte translateType = 0;
		
		
		if (0 == serviceId) {
			// 预存 发票张三(ID:12345678)预存金额【¥1000】单号YC202xxxxxxXXXXX申请【发票】，请当用户端点击【申请开票】后，管理端收到开票消息推送及时查看处理!
			content += "预存金额【" +money+ "】单号"+ orderSnId +"申请【发票】，请及时查看处理!";
			
			title = "开票通知(预存)";
			
			personal = "您的预存金额【￥" + money + "】单号" + orderSnId + "开票申请已提交，请耐心等待平台处理!";
			
//			您的预存金额【¥XXX】单号Y0202xxxxxxxxxXX已提交，请耐心等待平台处理
//			
			translateType = 1;
			
			
		} else {
			
			Byte invoiceContent = param.getInvoiceContent();
			
			String typeName = TransactionConst.Type[invoiceContent];
			PayManager payManager = payManagerService.getPayManager(param.getAssocId(),teamId);
			String typeServiceName = payManager.getServiceNames();
			content += "【" +typeServiceName+ "】订单"+ orderSnId +"已申请【发票】，请及时查看处理!";
			
			personal = "您的【"+typeServiceName+"】订单" + orderSnId + "开票申请已提交，请耐心等待平台处理。";
			
			title = "开票通知(订单)";
		}

		center.setNoticeContent(content);

		center.setPlatform((byte) 1);
		center.setTranslateType(translateType);

		center.setNoticeType((byte) 2);

		center.setTitle(title);

		center.setTypeId(orderInfo.getId());

		centerService.insert(center);
		
		////////////////////////////////////////////////////////////////
		
		center = new NoticeCenter();
		
		center.setUserId((int) userId);
		
		center.setJump((byte) 0);
		
		center.setTranslateType(translateType);

		center.setNoticeContent(personal);

		center.setPlatform((byte) 0);

		center.setNoticeType((byte) 2);

		center.setTitle(title);

		center.setTypeId(orderInfo.getId());
		
		int insert = centerService.insert(center);
		
		return ResponseModel.<Integer>success(insert);
	}

	@Override
	protected IBaseService<Translate> getBaseService() {
		return this.service;
	}

	/**
	 * 添加
	 * 
	 * @param <V>
	 * @param param
	 * @return
	 */
	@PostMapping("/update")
	public ResponseModel<Integer> update(@Validated @RequestBody TranslateUpdateParam param,
			HttpServletRequest httpServletRequest) {
		int res = this.service.parseUpdate(param, Translate.class);
		return ResponseModel.<Integer>success(res);
	}

	protected <VO> Class<VO> getTarget() {
		return (Class<VO>) TranslateVO.class;
	}

	@Resource
	public void setPayManagerService(IPayManagerService payManagerService) {
		this.payManagerService = payManagerService;
		
		orderInfoServer[1] = payManagerService;
	}
}